package com.vf.s.mvc.sync.common.util;

import com.jfinal.ext.kit.DateKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.vf.core.render.RenderBean;
import com.vf.s.common.model.biz.BizLayer;
import com.vf.s.common.model.biz.BizPoint;
import com.vf.s.common.model.sync.BizSyncDataTask;
import com.vf.s.mvc.sync.common.model.Point;
import com.vf.s.mvc.sync.common.task.http.HttpUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class FullUtil {
	
	protected final static Log LOG = Log.getLog(FullUtil.class);

	
	public  static void handle(BizLayer bizLayer,BizSyncDataTask task) {
		// 调用接口获取数据总量
		RenderBean result = null;
		if (StrKit.equals("GET", task.getMethod())) {
			result=HttpUtil.doGet(
					task.getUrl(), task.getId(), task.getCode(),task.getName(),
					DateKit.toStr(task.getLastTime(), "yyyy-MM-dd hh:mm:ss "),
					DateKit.toStr(task.getLastTime(), "yyyy-MM-dd hh:mm:ss ")
					,0,
					task.getParam(),1, task.getPageSize());
			
			if(result==null) {
				task.setNextTime(TimeUtil.getNextTime(task));
				task.update();
				LOG.debug(String.format("【%s】接口异常，不执行!!!", task.getName()));
				return;
			}
			
			if(result.getCode()!=200) {
				task.setNextTime(TimeUtil.getNextTime(task));
				task.update();
				LOG.debug(String.format("【%s】接口异常，不执行!!!", task.getName()));
				return;
			}
			
			try {
				JSONArray arrJSON = JSONArray.fromObject(result.getData());
				if(arrJSON!=null ) {
					BizPoint bizPoint,oldBizPoint;
					for(Object json :arrJSON) {
						Point point = (Point) JSONObject.toBean(JSONObject.fromObject(json), Point.class);
						if(point!=null) {
							if(!StrKit.equals("1", point.getIsDel())) {
								bizPoint=new BizPoint();
								bizPoint.setId(point.getId());
								bizPoint.setName(point.getName());
								bizPoint.setCode(point.getCode());
								bizPoint.setX(point.getX());
								bizPoint.setY(point.getY());
								bizPoint.setZ(point.getZ());
								bizPoint.setLayerId(bizLayer.getId());
								oldBizPoint=BizPoint.dao.findById(point.getId());
								if(oldBizPoint!=null) {
									if(bizPoint.update()) {
									}
								}else {
									if(bizPoint.save()) {
									}
								}
							}else {
								if(BizPoint.dao.deleteById(point.getId())) {
									Db.delete("delete from biz_point_filter where pointId=? ",point.getId());
								}
							}
						}
					}
					task.setLockTime(0);task.update();
				}else {
					task.setNextTime(TimeUtil.getNextTime(task));
					task.update();
					LOG.debug(String.format("【%s】接口异常，不执行!!!", task.getName()));
					return;
				}
			}catch (Exception e) {
				task.setStatus("0");
				task.update();
				LOG.debug(String.format("【%s】接口异常，停止执行!!!", task.getName()));
				return;
			}
		} else {
		}
	}

}
